//
//  SLDeviceInfo.m
//  SLEngine
//
//  Created by Victor on 14-12-16.
//  Copyright (c) 2014年 Sunline. All rights reserved.
//

#import "JFDeviceInfo.h"
#import <UIKit/UIKit.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import <sys/utsname.h>
#import "JFBasePri.h"
#import "JFBase.h"

#if __has_include(<SFHFKeychainUtils/SFHFKeychainUtils.h>)
#import <SFHFKeychainUtils/SFHFKeychainUtils.h>
#else
#import "SFHFKeychainUtils.h"
#endif

#define kKeychainServiceName "uuid.com.sunline.www"

#define kKeyServerNameUDID  @"kKeyServerNameUDID"
#define kKeyUserName        @"kKeyUserNameSTOPENUDID"
#define kUDIDKey            @"com.sunline.udidkey"


#define IOS_CELLULAR @"pdp_ip0"

#define IOS_WIFI @"en0"

#define IOS_VPN @"utun0"

#define IP_ADDR_IPv4 @"ipv4"

#define IP_ADDR_IPv6 @"ipv6"

#import <ifaddrs.h>

#import <arpa/inet.h>

#import <net/if.h>


NSString *uuid()
{
    CFUUIDRef puuid = CFUUIDCreate(nil);
    CFStringRef uuidString = CFUUIDCreateString(nil, puuid );
    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy(NULL, uuidString));
    CFRelease(puuid);
    CFRelease(uuidString);
    
    return result;
}

@implementation JFDeviceInfo

+ (NSDictionary *)deviceDictionary
{
    static NSMutableDictionary *s_dic;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        s_dic = [NSMutableDictionary dictionary];
        
        [s_dic setObject: [self deviceIdentifier] forKey: @"deviceCode"];
        [s_dic setObject: [self deviceName] forKey: @"deviceName"];
        [s_dic setObject: [self deviceModel] forKey: @"deviceUserName"];
        [s_dic setObject: [self deviceModelName] forKey: @"deviceModel"];
        [s_dic setObject: [self osName] forKey: @"osName"];
        [s_dic setObject: [self osVersion] forKey: @"osVersion"];
        [s_dic setObject: [self osType] forKey: @"osType"];
        [s_dic setObject: [self appVersion] forKey: @"appVersion"];
        [s_dic setObject: [self deviceType] forKey: @"deviceType"];
        [s_dic setObject: [self channel] forKey: @"channel"];
        [s_dic setObject: [self appBundleID] forKey: @"AppBuddleID"];
    });
    return s_dic;
}

+ (NSString *)channel
{
    if ([self isBenBen]) {
         return @"sunline";
    }else{
        return @"sunline-custom";
    }
}

+ (NSDictionary *)SLDeviceInfoDictionary
{
    static NSMutableDictionary *s_dic;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        s_dic = [NSMutableDictionary dictionary];
        
        [s_dic setObject: [self deviceIdentifier] forKey: @"uid"];
        [s_dic setObject: [self deviceName] forKey: @"deviceName"];
        [s_dic setObject: [self deviceModel] forKey: @"model"];
        [s_dic setObject: [self osName] forKey: @"system"];
        [s_dic setObject: [self osVersion] forKey: @"version"];
        [s_dic setObject: [self appVersion] forKey: @"appVersion"];
        [s_dic setObject: [self screenResolution] forKey: @"screenResolution"];
        [s_dic setObject: [self screenSize] forKey: @"screenSize"];
        [s_dic setObject: [self carrier] forKey: @"carrier"];
        
    });
    return s_dic;
}



#pragma mark - GETTER
+ (NSString *)appVersion
{
    /*
#if DEBUG
    NSArray *test = @[@"0.0.002", @"0.0.003", @"0.0.004", @"0.0.005"];
    static NSInteger i = 0;
    NSString *version = test[i];
    i++;
    i = i%4;
    return version;
#endif
     */
    return [[NSBundle mainBundle].infoDictionary objectForKey: @"CFBundleShortVersionString"];
}
+(NSString*)appBundleID{
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
}


+ (NSString *)appBuild {
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
}

+ (NSString *)deviceIdentifier
{
    NSString * udidFromKeychain  =[[self class] udidFromKeychain];
    NSString * userData = [NSString stringWithFormat:@"%@-%@",[self deviceName],[self deviceModel]];
    NSString * md5UserData = [[userData md5String] uppercaseString];
    udidFromKeychain = [NSString stringWithFormat:@"%@-%@",md5UserData,udidFromKeychain];
    return udidFromKeychain;//[[self class] udidFromKeychain];
}
+ (NSString *)deviceName
{
    return [UIDevice currentDevice].name;
}
+ (NSString *)deviceModel
{
    return [UIDevice currentDevice].model;
}
+ (NSNumber *)deviceType
{
    /* 0 PC
     * 1 phone
     * 2 pad
     */
    return @(1);
}
+ (NSString *)osName
{
    return [UIDevice currentDevice].systemName;
}
+ (NSString *)osVersion
{
    return [UIDevice currentDevice].systemVersion;
}
+ (NSNumber *)osType
{
    return @(1);
}

+ (NSString *)udidFromKeychain
{
    
    NSString *udid =[[NSUserDefaults standardUserDefaults] objectForKey:kUDIDKey];
    //如果应用内没有，从keychain拿
    if (![udid length]) {
        udid = [SFHFKeychainUtils getPasswordForUsernameOld: kKeyUserName
                                          andServiceName: kKeyServerNameUDID
                                                   error: nil];
        if ([udid length]) {
            [[NSUserDefaults standardUserDefaults] setObject:udid forKey:kUDIDKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
            return udid;
        }
    }else {//如果应用内有，keychain里面没有，同步一下数据到kaychain
        NSString *keychainUDID = [SFHFKeychainUtils getPasswordForUsernameOld: kKeyUserName
                                                            andServiceName: kKeyServerNameUDID
                                                                     error: nil];
        if (![keychainUDID length]) {
            [SFHFKeychainUtils storeUsername: kKeyUserName andPassword: udid
                              forServiceName: kKeyServerNameUDID
                              updateExisting: YES
                                       error: nil];
        }
    }


    //如果应用内，keychain都没有udid，则生成新的udid，并保存到应用内和keychain
    if (![udid length]) {
        [self storeUDIDToKeychain];
        udid = [[NSUserDefaults standardUserDefaults] objectForKey:kUDIDKey];
    }

    if (udid.length == 0) {
        udid = @"AnErrorPlaceholderUDID";
    }
    return udid;
}


+ (BOOL)storeUDIDToKeychain
{
    NSString *udid = nil;

    udid =[[NSUserDefaults standardUserDefaults] objectForKey:kUDIDKey];

    if ([udid length]) {
        return YES;
    }else {
        udid = [SFHFKeychainUtils getPasswordForUsernameOld: kKeyUserName
                                          andServiceName: kKeyServerNameUDID
                                                   error: nil];
        if ([udid length]) {
            return YES;
        }
    }

    if ([[UIDevice currentDevice] respondsToSelector:@selector(identifierForVendor)]) {
        NSUUID *uuid = [UIDevice currentDevice].identifierForVendor;
        udid = [uuid UUIDString];
    }else {
        udid = uuid();
    }
    if ([udid length]) {
        [[NSUserDefaults standardUserDefaults] setObject:udid forKey:kUDIDKey];
        [[NSUserDefaults standardUserDefaults] synchronize];

        [SFHFKeychainUtils storeUsername: kKeyUserName andPassword: udid
                          forServiceName: kKeyServerNameUDID
                          updateExisting: YES
                                   error: nil];
        return YES;
    }else {
        return NO;
    }
}

+ (NSString *)screenSize{

    CGSize size = [[UIScreen mainScreen] bounds].size;
    
    return [NSString stringWithFormat:@"%ldX%ld",(long)size.width,(long)size.height];
    
}

+ (NSString *)screenResolution{
    
    CGSize size = [[UIScreen mainScreen] bounds].size;
    
    CGFloat scale = [UIScreen mainScreen].scale;

    return [NSString stringWithFormat:@"%ldX%ld",(long)(size.width*scale),(long)(size.height*scale)];

}

+ (NSString *)carrier{
    //获取本机运营商名称
    
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    
    CTCarrier *carrier = [info subscriberCellularProvider];
    
    //当前手机所属运营商名称
    
    //先判断有没有SIM卡，如果没有则不获取本机运营商
    
    if (!carrier.isoCountryCode) {
        
       return  @"无运营商";
        
    }else{
        
       return  [carrier carrierName];
        
    }

}

+ (NSString *)deviceModelName{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *platform = [NSString stringWithCString:systemInfo.machine
                                            encoding:NSUTF8StringEncoding];
    //simulator
    if ([platform isEqualToString:@"i386"])          return @"Simulator";
    if ([platform isEqualToString:@"x86_64"])        return @"Simulator";
    
    //AirPods
    if ([platform isEqualToString:@"AirPods1,1"])    return @"AirPods";
    
    //Apple TV
    if ([platform isEqualToString:@"AppleTV2,1"])    return @"Apple TV (2nd generation)";
    if ([platform isEqualToString:@"AppleTV3,1"])    return @"Apple TV (3rd generation)";
    if ([platform isEqualToString:@"AppleTV3,2"])    return @"Apple TV (3rd generation)";
    if ([platform isEqualToString:@"AppleTV5,3"])    return @"Apple TV (4th generation)";
    if ([platform isEqualToString:@"AppleTV6,2"])    return @"Apple TV 4K";
    
    //Apple Watch
    if ([platform isEqualToString:@"Watch1,1"])    return @"Apple Watch (1st generation)";
    if ([platform isEqualToString:@"Watch1,2"])    return @"Apple Watch (1st generation)";
    if ([platform isEqualToString:@"Watch2,6"])    return @"Apple Watch Series 1";
    if ([platform isEqualToString:@"Watch2,7"])    return @"Apple Watch Series 1";
    if ([platform isEqualToString:@"Watch2,3"])    return @"Apple Watch Series 2";
    if ([platform isEqualToString:@"Watch2,4"])    return @"Apple Watch Series 2";
    if ([platform isEqualToString:@"Watch3,1"])    return @"Apple Watch Series 3";
    if ([platform isEqualToString:@"Watch3,2"])    return @"Apple Watch Series 3";
    if ([platform isEqualToString:@"Watch3,3"])    return @"Apple Watch Series 3";
    if ([platform isEqualToString:@"Watch3,4"])    return @"Apple Watch Series 3";
    
    //HomePod
    if ([platform isEqualToString:@"AudioAccessory1,1"])    return @"HomePod";
    
    //iPad
    if ([platform isEqualToString:@"iPad1,1"])    return @"iPad";
    if ([platform isEqualToString:@"iPad2,1"])    return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,2"])    return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,3"])    return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,4"])    return @"iPad 2";
    if ([platform isEqualToString:@"iPad3,1"])    return @"iPad (3rd generation)";
    if ([platform isEqualToString:@"iPad3,2"])    return @"iPad (3rd generation)";
    if ([platform isEqualToString:@"iPad3,3"])    return @"iPad (3rd generation)";
    if ([platform isEqualToString:@"iPad3,4"])    return @"iPad (4th generation)";
    if ([platform isEqualToString:@"iPad3,5"])    return @"iPad (4th generation)";
    if ([platform isEqualToString:@"iPad3,6"])    return @"iPad (4th generation)";
    if ([platform isEqualToString:@"iPad4,1"])    return @"iPad Air";
    if ([platform isEqualToString:@"iPad4,2"])    return @"iPad Air";
    if ([platform isEqualToString:@"iPad4,3"])    return @"iPad Air";
    if ([platform isEqualToString:@"iPad5,3"])    return @"iPad Air 2";
    if ([platform isEqualToString:@"iPad5,4"])    return @"iPad Air 2";
    if ([platform isEqualToString:@"iPad6,7"])    return @"iPad Pro (12.9-inch)";
    if ([platform isEqualToString:@"iPad6,8"])    return @"iPad Pro (12.9-inch)";
    if ([platform isEqualToString:@"iPad6,3"])    return @"iPad Pro (9.7-inch)";
    if ([platform isEqualToString:@"iPad6,4"])    return @"iPad Pro (9.7-inch)";
    if ([platform isEqualToString:@"iPad6,11"])    return @"iPad (5th generation)";
    if ([platform isEqualToString:@"iPad6,12"])    return @"iPad (5th generation)";
    if ([platform isEqualToString:@"iPad7,1"])    return @"iPad Pro (12.9-inch, 2nd generation)";
    if ([platform isEqualToString:@"iPad7,2"])    return @"iPad Pro (12.9-inch, 2nd generation)";
    if ([platform isEqualToString:@"iPad7,3"])    return @"iPad Pro (10.5-inch)";
    if ([platform isEqualToString:@"iPad7,4"])    return @"iPad Pro (10.5-inch)";
    if ([platform isEqualToString:@"iPad7,5"])    return @"iPad (6th generation)";
    if ([platform isEqualToString:@"iPad7,6"])    return @"iPad (6th generation)";
    
    //iPad mini
    if ([platform isEqualToString:@"iPad2,5"])    return @"iPad mini";
    if ([platform isEqualToString:@"iPad2,6"])    return @"iPad mini";
    if ([platform isEqualToString:@"iPad2,7"])    return @"iPad mini";
    if ([platform isEqualToString:@"iPad4,4"])    return @"iPad mini 2";
    if ([platform isEqualToString:@"iPad4,5"])    return @"iPad mini 2";
    if ([platform isEqualToString:@"iPad4,6"])    return @"iPad mini 2";
    if ([platform isEqualToString:@"iPad4,7"])    return @"iPad mini 3";
    if ([platform isEqualToString:@"iPad4,8"])    return @"iPad mini 3";
    if ([platform isEqualToString:@"iPad4,9"])    return @"iPad mini 3";
    if ([platform isEqualToString:@"iPad5,1"])    return @"iPad mini 4";
    if ([platform isEqualToString:@"iPad5,2"])    return @"iPad mini 4";
    
    //iPhone
    if ([platform isEqualToString:@"iPhone1,1"])     return @"iPhone 1G";
    if ([platform isEqualToString:@"iPhone1,2"])     return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"])     return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"])     return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,2"])     return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone4,1"])     return @"iPhone 4S";
    if ([platform isEqualToString:@"iPhone5,1"])     return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,2"])     return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,3"])     return @"iPhone 5C";
    if ([platform isEqualToString:@"iPhone5,4"])     return @"iPhone 5C";
    if ([platform isEqualToString:@"iPhone6,1"])     return @"iPhone 5S";
    if ([platform isEqualToString:@"iPhone6,2"])     return @"iPhone 5S";
    if ([platform isEqualToString:@"iPhone7,1"])     return @"iPhone 6 Plus";
    if ([platform isEqualToString:@"iPhone7,2"])     return @"iPhone 6";
    if ([platform isEqualToString:@"iPhone8,1"])     return @"iPhone 6s";
    if ([platform isEqualToString:@"iPhone8,2"])     return @"iPhone 6s Plus";
    if ([platform isEqualToString:@"iPhone8,4"])     return @"iPhone SE";
    if ([platform isEqualToString:@"iPhone9,1"])     return @"iPhone 7";
    if ([platform isEqualToString:@"iPhone9,3"])     return @"iPhone 7";
    if ([platform isEqualToString:@"iPhone9,2"])     return @"iPhone 7 Plus";
    if ([platform isEqualToString:@"iPhone9,4"])     return @"iPhone 7 Plus";
    if ([platform isEqualToString:@"iPhone10,1"])    return @"iPhone 8";
    if ([platform isEqualToString:@"iPhone10,4"])    return @"iPhone 8";
    if ([platform isEqualToString:@"iPhone10,2"])    return @"iPhone 8 Plus";
    if ([platform isEqualToString:@"iPhone10,5"])    return @"iPhone 8 Plus";
    if ([platform isEqualToString:@"iPhone10,3"])    return @"iPhone X";
    if ([platform isEqualToString:@"iPhone10,6"])    return @"iPhone X";
    if ([platform isEqualToString:@"iPhone11,8"])    return @"iPhone XR";
    if ([platform isEqualToString:@"iPhone11,2"])    return @"iPhone XS";
    if ([platform isEqualToString:@"iPhone11,4"])    return @"iPhone XS Max";
    if ([platform isEqualToString:@"iPhone11,6"])    return @"iPhone XS Max";
    if ([platform isEqualToString:@"iPhone12,1"])    return @"iPhone 11";
    if ([platform isEqualToString:@"iPhone12,3"])    return @"iPhone 11 Pro";
    if ([platform isEqualToString:@"iPhone12,5"])    return @"iPhone 11 Pro Max";

    //iPod touch
    if ([platform isEqualToString:@"iPod1,1"])    return @"iPod touch";
    if ([platform isEqualToString:@"iPod2,1"])    return @"iPod touch (2nd generation)";
    if ([platform isEqualToString:@"iPod3,1"])    return @"iPod touch (3rd generation)";
    if ([platform isEqualToString:@"iPod4,1"])    return @"iPod touch (4th generation)";
    if ([platform isEqualToString:@"iPod5,1"])    return @"iPod touch (5th generation)";
    if ([platform isEqualToString:@"iPod7,1"])    return @"iPod touch (6th generation)";
    
    return platform;
    
}
//是否是全面屏
+ (BOOL)isFullScreen{
    
    if (@available(iOS 11.0, *)) {
        UIWindow * windows =[[UIApplication sharedApplication].delegate window];
        if ( windows.safeAreaInsets.bottom == 34) {
            return YES;
        }else{
            return NO;
        }
    }

    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *platform = [NSString stringWithCString:systemInfo.machine
                                            encoding:NSUTF8StringEncoding];
    BOOL flag = false;
    if ([platform isEqualToString:@"iPhone10,3"])    flag =true;
    if ([platform isEqualToString:@"iPhone10,6"])    flag =true;
    if ([platform isEqualToString:@"iPhone11,8"])    flag =true;
    if ([platform isEqualToString:@"iPhone11,2"])    flag =true;
    if ([platform isEqualToString:@"iPhone11,4"])    flag =true;
    if ([platform isEqualToString:@"iPhone11,6"])    flag =true;
    return flag;
}

+ (BOOL)isBenBen{
    if ([@"com.9fbank.zhengquan" isEqualToString:[self appBundleID]]) {
        return NO;
    }else{
        return YES;
    }
}

//+(NSString *)modelUUID{
//    return [self]
//}
#pragma mark--IPV6相关
+ (BOOL)isIpv6{
    NSArray *searchArray =
  @[ IOS_VPN @"/" IP_ADDR_IPv6,
     IOS_VPN @"/" IP_ADDR_IPv4,
     IOS_WIFI @"/" IP_ADDR_IPv6,
     IOS_WIFI @"/" IP_ADDR_IPv4,
     IOS_CELLULAR @"/" IP_ADDR_IPv6,
     IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
    
    NSDictionary *addresses = [self getIPAddresses];
    __block BOOL isIpv6 = NO;
    [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
    {if ([key rangeOfString:@"ipv6"].length > 0 && ![[NSString stringWithFormat:@"%@",addresses[key]] hasPrefix:@"(null)"] ) {
        if ( ![addresses[key] hasPrefix:@"fe80"]) {
            isIpv6 = YES;
        }
    }
    } ];
    return isIpv6;
}
+ (NSDictionary *)getIPAddresses
{
    NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
    struct ifaddrs *interfaces;
    
    if(!getifaddrs(&interfaces)) {
        struct ifaddrs *interface;
        
        for(interface=interfaces; interface; interface=interface->ifa_next) {
            
            if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
                continue; // deeply nested code harder to read
            }
            const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
            if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
                NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
                NSString *type;
                if(addr->sin_family == AF_INET) {
                    if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv4;
                    }
                } else {
                    const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
                    if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv6;
                    }
                }
                if(type) {
                    NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
                    addresses[key] = [NSString stringWithUTF8String:addrBuf];
                }
            }
        }
        freeifaddrs(interfaces);
    }
    return [addresses count] ? addresses : nil;
}

@end
